import Loading from "../Base/Loading";
import { resMgr } from "./ResMgr";

class LoadingMgr {

    public static instance: LoadingMgr = null
    public static getInstance() {
        if (!LoadingMgr.instance) {
            LoadingMgr.instance = new LoadingMgr()
        }
        return LoadingMgr.instance
    }

    private _loadingView: Loading = null
    private _rootNode: cc.Node = null

    public initRoot(root: cc.Node) {
        this._rootNode = root.getChildByName("loadingRoot")
        if (!this._loadingView) {
            resMgr.load("Prefab/Common/Loading", cc.Prefab).then((res: cc.Prefab) => {
                if (res) {
                    if (!this._loadingView && this._rootNode) {
                        let node = cc.instantiate(res)
                        let view = node.getComponent("Loading")
                        this._rootNode.addChild(node)
                        node.active = false
                        this._loadingView = view
                    }
                }
            })
        } else {
            this._rootNode.addChild(this._loadingView.node)
            this._loadingView.node.active = false
        }
    }

    dispose() {
        if (this._loadingView) {
            this._loadingView.forceHide()
            this._loadingView.node.removeFromParent()
        }
        this._rootNode = null
    }

    /**
     * 显示loading
     */
    public showLoading() {
        this._loadingView?.show()
    }

    /**
     * 隐藏loading界面 
     */
    public hideLoading() {
        this._loadingView?.hide()
    }
}

export let loadingMgr = LoadingMgr.getInstance()
